package com.takepoints21.mobile;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;

import com.takepoints.android.bo.Promotion;
import com.takepoints.android.bo.SiteInfoPromotion;
import com.takepoints.android.services.PublicServices;
import com.takepoints.android.util.AnimationUtil;
import com.takepoints.android.util.DownloadImageTask;

public class TPRewards extends BaseActivity {
	
	private ListView lstPromotions = null;
	private PromoListAdapter promoAdapter = null;
	
	private Button btnLoadMore = null;
	private int nextPage = 1;
	private boolean isProcessing = false;
	
	private final String IMG_URL = "https://www.takepoints.com/public/uploads/tmobile/";
	
	public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.promotions);
        
        ImageView imgLogo = (ImageView)findViewById(R.id.imgLogo);
        imgLogo.setImageResource(R.drawable.header_rewards);
        
        TextView txtHeader = (TextView)findViewById(R.id.txtHeader);
        txtHeader.setText(R.string.title_reward);
        manageMenu(0);
        
        btnLoadMore = (Button)findViewById(R.id.btnLoadMore);
        btnLoadMore.setOnClickListener(new View.OnClickListener(){
			 public void onClick(View view) {
				 new FetchRewards().execute(String.valueOf(nextPage));
			 }
        });
        btnLoadMore.bringToFront();
        
        ImageView imgRefresh = (ImageView)findViewById(R.id.imgRefresh);
        imgRefresh.setOnClickListener(new View.OnClickListener(){
			 public void onClick(View view) {
				 nextPage = 1;
				 if( !btnLoadMore.isShown() ){
					 btnLoadMore.setVisibility(View.VISIBLE);
				 }
				 promoAdapter.removeAll();
				 new FetchRewards().execute("1");
			 }
        });
        
        lstPromotions = (ListView)findViewById(R.id.lstPromotions);
        lstPromotions.setLayoutAnimation(new AnimationUtil().getSlideDownAnimateCtrl());
        
        promoAdapter = new PromoListAdapter(new ArrayList<Promotion>());
        lstPromotions.setAdapter(promoAdapter);
        
        new FetchRewards().execute("1");
	}
	
	private class PromoListAdapter extends BaseAdapter {
		private List<Promotion> promotions;
		private LayoutInflater mInflater;

		public PromoListAdapter(List<Promotion> promotions){
			mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.promotions = promotions;
		}
		
		public void add(Promotion promotion){
			promotions.add(promotion);
			notifyDataSetChanged();
		}
		
		public void removeAll(){
			promotions.clear();
			notifyDataSetChanged();
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			if(convertView == null){
				convertView = mInflater.inflate(R.layout.myitemrow, null);
			}
			final Promotion promotion = promotions.get(position);
			if(promotion != null){
				final TableRow tblCard = (TableRow)convertView.findViewById(R.id.tblCard);
				
				ImageView imgCard = (ImageView)convertView.findViewById(R.id.imgCard);
				if(imgCard != null){
					Bitmap bitmap = BitmapFactory.decodeFile(IMG_CACHE_PATH + promotion.getPicture());
					if(bitmap != null){
						imgCard.setImageBitmap(bitmap);
					} else{
						imgCard.setTag(IMG_URL + promotion.getPicture());
						new DownloadImageTask().execute(imgCard);
					}
				}
				
				LinearLayout lnrDetail = (LinearLayout)convertView.findViewById(R.id.lnrDetail);
				lnrDetail.removeAllViews();
				if(lnrDetail != null){
					TextView txtTitle = new TextView(lnrDetail.getContext());
					txtTitle.setText(promotion.getTitleName());
					txtTitle.setTextSize(12);
					txtTitle.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
					txtTitle.setTextColor(Color.parseColor("#78a023"));
					txtTitle.setHeight(LayoutParams.WRAP_CONTENT);
					txtTitle.setPadding(10, 1, 1, 1);
					txtTitle.setSingleLine(false);
					lnrDetail.addView(txtTitle);
					
					TextView txt1 = new TextView(lnrDetail.getContext());
					txt1.setText("แต้มที่ใช้แลก  " + promotion.getOfferPts() + " แต้ม");
					txt1.setTextSize(11);
					txt1.setTextColor(Color.parseColor("#404a4a"));
        	        txt1.setHeight(LayoutParams.WRAP_CONTENT);
					txt1.setPadding(9, 1, 1, 1);
					txt1.setSingleLine(false);
					lnrDetail.addView(txt1);
					
					TextView txtPointGet = new TextView(lnrDetail.getContext());
					txtPointGet.setText("ภายในวันที่  " + promotion.getExpiryDate());
					txtPointGet.setTextSize(9);
					txtPointGet.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
					txtPointGet.setTextColor(Color.parseColor("#f7941d"));
					txtPointGet.setPadding(10, 3, 1, 1);
					lnrDetail.addView(txtPointGet);
				}
				
				convertView.setOnClickListener(new View.OnClickListener(){
					 public void onClick(View view) {
						 Intent promoDetailInt = new Intent(view.getContext(), TPPromoDetail.class);
						 promoDetailInt.putExtra("promoId", Integer.parseInt(promotion.getPromotionId()));
						 promoDetailInt.putExtra("promoTypeId", Integer.parseInt(promotion.getPromoTypeId()));
						 promoDetailInt.putExtra("picture", promotion.getPicture());
						 startActivityForResult(promoDetailInt, 0);
					 }
				});
				convertView.setOnTouchListener(new View.OnTouchListener(){
					 public boolean onTouch(View v, MotionEvent event){
						 int action = event.getAction();
						 switch(action){
						 	case MotionEvent.ACTION_DOWN:
						 		tblCard.setBackgroundColor(Color.LTGRAY);
						 		break;
						 	case MotionEvent.ACTION_UP:
						 		tblCard.setBackgroundResource(R.drawable.bglist);
						 		break;
						 	case MotionEvent.ACTION_MOVE:
						 		tblCard.setBackgroundResource(R.drawable.bglist);
						 		break;
						 	case MotionEvent.ACTION_CANCEL:
						 		//tblCard.setBackgroundColor(Color.parseColor("#9aa1a0"));
						 		tblCard.setBackgroundResource(R.drawable.bglist);
						 		break;
						 	default:
						 		break;
						 }
						 return false;
					}
				 });
			}
			return convertView;
		}

		@Override
		public int getCount() {
			return promotions.size();
		}

		@Override
		public Object getItem(int position) {
			return promotions.get(position);
		}

		@Override
		public long getItemId(int position) {
			return promotions.get(position).hashCode();
		}
	}
	
	class FetchRewards extends AsyncTask<String, Void, List<Promotion>>{
    	
		private ImageView imgRefresh = null;
		
        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            isProcessing = true;
            imgRefresh = (ImageView)findViewById(R.id.imgRefresh);
            imgRefresh.startAnimation(new AnimationUtil().getRotateAnimation(25f, 25f));
        }
        
        @Override
        protected List<Promotion> doInBackground(String... params){
        	final int page = Integer.parseInt(params[0]);
        	List<Promotion> promoL = PublicServices.getPromotionList(PublicServices.PROMOTION_TYPE_REWARD, page);
        	return promoL;
        }
        
        @Override
        protected void onPostExecute(List<Promotion> result){
        	int rows = (result==null)?0:result.size();
        	if(rows > 0){
	    		try{
	    			for(int i=0; i<rows; i++){
	    				promoAdapter.add(result.get(i));
	    			}
	    			
	    			if(rows > 0){
	    				Promotion info = result.get(0);
	    	            ++nextPage;
	    	            if(nextPage > info.getTotalPage()){
	    	            	btnLoadMore.setVisibility(View.GONE);
	    	            }
	            	} else{
	            		btnLoadMore.setVisibility(View.GONE);
	            	}
	    		} catch(Exception e){
	    			alert("ผิดพลาด : " + e.getMessage());
	    		}
        	}
    		imgRefresh.clearAnimation();
    		isProcessing = false;
        }
        
    }
	
}
